<template>
  <div class="ele-body">
    <div class="bg-fff padding-30">
      <a-form
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="会员" v-bind="validateInfos.member_id">
              <div class="flex align-center justify-between">
                <a-input-search
                  placeholder="请输入"
                  class="flex1 margin-right-10"
                  v-model:value="form.mobile"
                  @search="searchMember"
                />
                <div
                  class="add-btn flex align-center justify-center hands"
                  style="width: 32px"
                  @click="showEdit = true"
                  >+</div
                >
              </div>
            </a-form-item>
            <a-form-item label="会员信息" v-if="memberInfo.name">
              <div class="solid padding-6">
                <div class="flex align-center">
                  <a-image
                    :width="30"
                    :height="30"
                    :src="memberInfo.thumb_url"
                  />
                  <div class="flex1 margin-left-15">
                    <div class="fs-12"
                      >{{ memberInfo.name || '' }}
                      <span v-if="memberInfo.nickname"
                        >({{ memberInfo.nickname || '' }})</span
                      ></div
                    >
                    <div class="fs-12 margin-top-10"
                      >手机号：{{ memberInfo.mobile || '' }}</div
                    >
                  </div>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="维修项目">
              <a-select
                optionFilterProp="label"
                :options="repairOptions"
                allow-clear
                v-model:value="form.repair_item_code"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="原消费单">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.origin_order_sn"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="取货方式">
              <a-select
                optionFilterProp="label"
                :options="getOptions"
                allow-clear
                v-model:value="form.receive_type"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="购买日期">
              <a-date-picker
                class="ele-fluid"
                valueFormat="YYYY/MM/DD"
                placeholder="请选择购买日期"
                v-model:value="form.sales_time"
                autocomplete="off"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24" :xs="24">
            <div class="solid margin-bottom-30"></div>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="货品条码">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.bar_code"
                autocomplete="off"
                @change="inpChange"
              />
            </a-form-item>
            <a-form-item label="货重(g)">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.piece_weight"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="成色">
              <a-select
                optionFilterProp="label"
                :options="qualityOptions"
                allow-clear
                v-model:value="form.quality_code"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="主石名称">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.main_stone_name"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="主石颜色">
              <a-select
                optionFilterProp="label"
                :options="gemattributeOpt1"
                allow-clear
                v-model:value="form.main_stone_color"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="主石切工">
              <a-select
                optionFilterProp="label"
                :options="gemattributeOpt3"
                allow-clear
                v-model:value="form.main_stone_cut"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="故障描述">
              <a-textarea
                allow-clear
                v-model:value="form.desc"
                placeholder="请输入"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="图片">
			<div class="flex align-center">
				  <a-upload
				  name="attachment"
					v-model:file-list="fileList"
					:limit="5"
					:action="uploadUrl"
					list-type="picture-card"
					@change="uploadHandler"
					@preview="handlePreview"
				  >
					<!-- <img
					  v-if="imageUrl"
					  :src="imageUrl"
					  style="width: 100%"
					  alt="example"
					/> -->
					<div v-if="fileList.length < 6">
					  <loading-outlined v-if="loading" />
					  <plus-outlined v-else />
					</div>
				  </a-upload>
			  </div>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="货品名称" v-bind="validateInfos.name">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.name"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="货品小类">
              <a-select
                optionFilterProp="label"
                :options="subclassOptions"
                allow-clear
                v-model:value="form.subclass_code"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="品类">
              <a-select
                optionFilterProp="label"
                :options="classesOptions"
                allow-clear
                v-model:value="form.classes_code"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="主石重(t)">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.main_stone_weight"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="主石净度">
              <a-select
                optionFilterProp="label"
                :options="gemattributeOpt2"
                allow-clear
                v-model:value="form.main_stone_neatness"
                placeholder="请选择"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="货品估价">
              <a-input
                allow-clear
                placeholder="请输入"
                v-model:value="form.evaluate"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="备注">
              <a-textarea
                allow-clear
                v-model:value="form.note"
                placeholder="请输入"
                autocomplete="off"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div style="width: 100%; height: 80px"></div>
    <div class="ele-bottom-tool" style="padding-right: 40px">
      <div class="ele-bottom-tool-actions">
        <a-space size="small">
          <a-button type="primary" @click="save()">确认</a-button>
          <a-button type="primary" @click="save('next')">保存并处理</a-button>
          <a-button @click="cancel()">取消</a-button>
        </a-space>
      </div>
    </div>
    <!-- 选择会员弹窗 -->
    <select-member
      v-if="showMember"
      :memberVal="memberVal"
      v-model:visible="showMember"
      @getMember="getMember"
    />
    <!-- 维修处理弹窗 -->
    <repair
      v-if="showRepair"
      v-model:visible="showRepair"
      :order_sn="order_sn"
      @done="done"
    />
    <!-- 完成维修弹窗 -->
    <over
      v-if="showOver"
      v-model:visible="showOver"
      :order_sn="order_sn"
      @done="done"
    />
    <!-- 支付弹窗 -->
    <pay
      v-if="showPay"
      v-model:visible="showPay"
      :order_sn="order_sn"
      :money="money"
      from="repair"
      @done="done"
    />
    <!-- 新建会员 -->
    <user-edit
      v-if="showEdit"
      actionStatus="add"
      v-model:visible="showEdit"
      :memberVal="form.mobile"
      @done="addMember"
    />
	
	<a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
	      <img alt="example" style="width: 100%" :src="previewImage" />
	</a-modal>
  </div>
</template>

<script setup>
	function getBase64(file) {
	  return new Promise((resolve, reject) => {
	    const reader = new FileReader();
	    reader.readAsDataURL(file);
	    reader.onload = () => resolve(reader.result);
	    reader.onerror = error => reject(error);
	  });
	}
  import { ref, unref, reactive, onMounted } from 'vue';
  import { Form } from 'ant-design-vue';
  import { uploadUrl } from '@/config/setting';
  import { emailReg, phoneReg, identityReg } from 'ele-admin-pro';
  import { message, Modal } from 'ant-design-vue';
  import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  import { useRouter } from 'vue-router';
  import { actionFn } from '@/utils/action.js';
  import selectMember from '../../order/jewelry_order/components/select-member.vue';
  import repair from '../get_list/components/repair.vue';
  import over from '../get_list/components/over.vue';
  import pay from '../../order/jewelry_order/components/pay.vue';
  import userEdit from '@/views/member/member/get_list/components/user-edit.vue';
  import {
    get_role_select,
    get_repair_item_select,
    get_quality_select,
    get_gem_attribute_select,
    get_classes_select,
    get_subclass_select
  } from '@/api/material/select';
  import {
    repair_order_add,
    repair_order_edit,
    get_repair_order_detail
  } from '@/api/order/repair_order';
  import { goods_info } from '@/api/jewelry/goods_info';
  import { add } from '@/api/member/get_list';

  const { currentRoute, push } = useRouter();
  const { query } = unref(currentRoute);

  // 表格列配置
  const useForm = Form.useForm;

  const props = defineProps({
    // 弹窗是否打开
    visible: Boolean
  });

  const emit = defineEmits(['done', 'update:visible']);
  // 提交状态
  const loading = ref(false);
  const actionData = ref({});
  const order_sn = ref(null);
  const showRepair = ref(false);
  const showOver = ref(false);
  const showPay = ref(false);
  const money = ref(null);
  const showEdit = ref(false);

  // 表单数据
  const form = reactive({
    member_id: '',
    mobile: '',
    order_sn: '',
    origin_order_sn: '',
    receive_type: null,
    repair_item_code: null,
    sales_time: '',
    bar_code: '',
    name: '',
    piece_weight: '',
    subclass_code: null,
    quality_code: null,
    classes_code: null,
    main_stone_name: '',
    main_stone_weight: '',
    main_stone_color: null,
    main_stone_neatness: null,
    main_stone_cut: null,
    evaluate: '',
    desc: '',
    note: '',
    imgs: ''
  });
  const showMember = ref(false);
  const memberVal = ref(null);
  const memberInfo = ref({});

  const repairOptions = ref([]);
  const qualityOptions = ref([]);
  const gemattributeOpt1 = ref([]);
  const gemattributeOpt2 = ref([]);
  const gemattributeOpt3 = ref([]);
  const classesOptions = ref([]);
  const subclassOptions = ref([]);
  const getOptions = ref([
    { value: '1', label: '自提' },
    { value: '2', label: '快递' }
  ]);
  onMounted(() => {
    get_repair_item_select({ page: 1, page_size: 99999 }).then((res) => {
      repairOptions.value = res;
    });
    get_quality_select({ page: 1, page_size: 99999 }).then((res) => {
      qualityOptions.value = res;
    });
    get_classes_select({ page: 1, page_size: 99999 }).then((res) => {
      classesOptions.value = res;
    });
    get_subclass_select({ page: 1, page_size: 99999 }).then((res) => {
      subclassOptions.value = res;
    });
    getAttr();
    if (query.order_sn) {
      getDetail();
    }
  });

  const getDetail = () => {
    get_repair_order_detail({ order_sn: query.order_sn }).then((res) => {
      Object.keys(form).forEach((key) => {
        form[key] = res[key] ? res[key] : null;
      });
      form.member_id = res.id;
      //images2.value = res.img_url;
	  let arr = res.imgs ? res.imgs.split(',') : [];
	  res.img_url.forEach((item, index)=>{
		images2.value.push({
			id: arr[index],
			url:item
		})
		fileList.value.push({
			id: arr[index],
			url:item
		})
	  })
	  console.log('====', images2.value)
    });
  };
  const getAttr = () => {
    get_gem_attribute_select({
      page: 1,
      page_size: 9999,
      filters: { type: 'color' }
    }).then((res) => {
      gemattributeOpt1.value = res;
    });
    get_gem_attribute_select({
      page: 1,
      page_size: 9999,
      filters: { type: 'neatness' }
    }).then((res) => {
      gemattributeOpt2.value = res;
    });
    get_gem_attribute_select({
      page: 1,
      page_size: 9999,
      filters: { type: 'cut' }
    }).then((res) => {
      gemattributeOpt3.value = res;
    });
  };
  const inpChange = (e) => {
    setTimeout(() => {
      goods_info({
        bar_code: e.target.value
      }).then((res) => {
        if (res.sku_info && res.sku_info.length > 0) {
          res.sku_info.forEach((item) => {
            if (item.column == 'name') {
              form.name = item.value;
            }
            if (item.column == 'piece_weight') {
              form.piece_weight = item.value;
            }
            if (item.column == 'subclass_code') {
              form.subclass_code = item.value;
            }
            if (item.column == 'quality_code') {
              form.quality_code = item.value;
            }
            if (item.column == 'classes_code') {
              form.classes_code = item.value;
            }
          });
          if (res.master_gem.row_list.length > 0) {
            let main = res.master_gem.row_list[0];
            form.main_stone_name = main.stone_name;
            form.main_stone_weight = main.weight;
            form.main_stone_color = main.color;
            form.main_stone_neatness = main.neatness.toString();
            form.main_stone_cut = main.cut;
          }
        }
      });
    }, 1000);
  };

  const searchMember = (e) => {
    memberVal.value = e;
    showMember.value = true;
  };
  const getMember = (val) => {
    console.log('val===', val);
    memberInfo.value = val;
    form.member_id = val.id;
    form.mobile = val.mobile;
    showMember.value = false;
  };

  const imageUrl = ref('');

  // 头像上传
  const images = ref([]);
  // 营业执照上传
  const fileList = ref([]);
  const images2 = ref([]);
  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');
  /* 完全自己控制选择文件后的处理 */
  const uploadHandler = (info) => {
    if (info && info.file && info.file.response) {
      const data = info.file.response.data;
	  console.log('data==', info)
	  if(info.file.status == 'done'){
		  images2.value.push({
			  id:data.id,
			  url:data.path
		  });
	  }
	  if(info.file.status == 'removed'){
	  		images2.value.forEach((item, index)=>{
			 if(item.id == data.id){
				 images2.value.splice(index, 1);
			 }
	  		});
	  }
     // form.imgs = data.id.toString();
    }
  };
  const handleCancel = () => {
        previewVisible.value = false;
        previewTitle.value = '';
      };
      const handlePreview = async file => {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        previewImage.value = file.url || file.preview;
        previewVisible.value = true;
        previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
      };

  // 表单验证规则
  const rules = reactive({
    member_id: [
      {
        required: true,
        message: '请选择会员',
        type: 'number',
        trigger: 'change'
      }
    ],
    name: [
      {
        required: true,
        message: '请输入货品名称',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const { validate, validateInfos } = useForm(form, rules);
  /* 保存编辑 */
  const save = (type) => {
	  let arr = []
	  images2.value.forEach((item, index)=>{
	   arr.push(item.id);
	  });
	  form.imgs = arr.join(',');
    validate()
      .then(() => {
        if (query.order_sn) {
          repair_order_edit(form)
            .then((res) => {
              message.success(res.msg);
              push({
                path: '/order/repair_order/get_list'
              });
            })
            .catch((e) => {
              message.error(e);
            });
        } else {
          repair_order_add(form)
            .then((res) => {
              message.success(res.msg);
              if (type && type == 'next') {
                order_sn.value = res.data.order_sn;
                money.value = res.data.real_amount;
                actionData.value.url = 'order/repair_order/handle';
                showRepair.value = true;
              } else {
                push({
                  path: '/order/repair_order/get_list'
                });
              }
            })
            .catch((e) => {
              message.error(e);
            });
        }
      })
      .catch(() => {});
  };
  const cancel = () => {
    push({
      path: '/order/repair_order/get_list'
    });
  };
  const done = (form) => {
    if (form.type && form.type == 'next1') {
      actionFn(actionData.value, form, next1);
    } else if (form.type && form.type == 'next2') {
      money.value = form.real_amount;
      actionFn(actionData.value, form, next2);
    } else {
      actionFn(actionData.value, form, cancel);
    }
  };
  const next1 = () => {
    console.log('next1==11==');
    actionData.value.url = 'order/repair_order/complete';
    showRepair.value = false;
    showOver.value = true;
  };
  const next2 = () => {
    console.log('next2==22==');
    actionData.value.url = 'order/repair_order/pay';
    showOver.value = false;
    showPay.value = true;
  };
  const reloadTable = () => {
    showRepair.value = false;
    showOver.value = false;
    showPay.value = false;
    getDetail();
  };

  const addMember = (form) => {
    add(form)
      .then((res) => {
        showEdit.value = false;
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e);
      });
  };
</script>
<style scoped></style>
